//
//  VBOauthViewController.swift
//  VBo
//
//  Created by 赵世得 on 2016/10/24.
//  Copyright © 2016年 Zh. All rights reserved.
//

import UIKit
import YYModel

class VBOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
    }
    
    @objc private func cancelClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillClick(){
        let jsString = "document.getElementById('userId').value='\(VBNAME)',document.getElementById('passwd').value='\(VBPASSWORD)'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    private func setUpUI(){
        view.backgroundColor = UIColor.white
        setUpNav()
    }
    
    private func setUpNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(setImg: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(setImg: nil, title: "自动填充", target: self, action: #selector(autoFillClick))
        navigationItem.title = "微博登录"
    }
    private lazy var webView: UIWebView = {
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(VBAPPKEY)&redirect_uri=\(VBREDIRECTURI)")!
        let request = URLRequest(url: url)
        let view = UIWebView()
        view.delegate = self
        view.loadRequest(request)
        return view
        
    }()
}
extension VBOauthViewController: UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url?.absoluteString
        if let u = urlString, u.hasPrefix(VBREDIRECTURI) {
            let quey = request.url?.query
            if let q = quey {
                let code  = q.substring(from: "code=".endIndex)
                VBUserAccountViewModel.sharedTools.getUserAccount(code: code, finish: { (isSuccess) in
                    if !isSuccess{
                        print("请求失败")
                        return
                    }
                    print("请求成功")
                })
            }
            
        }
        return true
    }
}














